import { Component } from "react";
class DemoA extends Component {
    constructor() {
        super()
        this.state = {
            todo: "",
            list: []
        }
    }
    gettodo(e) {
        this.setState({
            todo: e.target.value
        })
    }
    confirm() {
        if (!this.state.todo.trim()) {
            alert('输入框必须有内容')
        }
        // console.log(this.state.todo);
        this.setState(_ => ({
            list: [..._.list, { id: Date.now(), task: _.todo }]
        }))
        // 键入后删除原有的
        this.setState({ todo: "" })
    }
    addByEnter(e) {
        if (e.keyCode === 13) {
            this.confirm()
        }

    }
    delTodo(a) {
        this.setState(state => ({
            list: state.list.filter(item => item.id != a)
        }))
    }
    render() {
        let { todo, list } = this.state
        return (
            <>
                <div>
                    <input
                        type="text"
                        value={todo}
                        onChange={(e) => this.gettodo(e)}
                        onKeyUp={e => this.addByEnter(e)}
                    ></input>
                    <button onClick={(e) => this.confirm(e)}>键入</button>
                </div>
                <div>
                    {/* 用{}来放数组 */}
                    {
                        list.map(item => (
                            <div key={item.id}><span>{item.id}</span>--<span>{item.task}</span>
                                <button onClick={() => this.delTodo(item.id)}>删除</button>
                            </div>

                        ))
                    }
                </div>
            </>
        )
    }
}

export default DemoA;